import re

from flask import request, current_app, jsonify, make_response
from info import redis_store, constants
from info.lib.yuntongxun.sms import CCP
from info.models import User
from info.utils.response_code import RET
from . import passport_bp
from info.utils.captcha.captcha import captcha


@passport_bp.route("/image_code")
def set_image_code():
    # 1获取参数
    code_id = request.args.get("code_id")
    # 2校验参数
    if not code_id:
        current_app.logger.error("参数错误")
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3逻辑处理
    image_name, image_code, image_data = captcha.generate_captcha()
    # real_image_code = captcha()
    # 4返回值
    try:
        redis_store.setex("Image_" + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, image_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    response = make_response(image_data)
    # 设置响应头告诉浏览器
    response.headers["Content-Type"] = "image/JPEG"
    return response


@passport_bp.route("/sms_code", methods=["POST"])
def get_sms_code():
    # 1获取三个参数手机号码,image_code_id,image_code
    params = request.json
    mobile = params.get("mobile")
    image_code = params.get("image_code")
    image_code_id = params.get("image_code_id")
    # 2判断参数
    if not all([mobile, image_code_id, image_code]):
        current_app.logger.error("参数不足")
        return jsonify(errno=RET.NODATA, errmsg="参数不足")
    if not re.match("1[35789][0-9]{9}", mobile):
        current_app.logger.error("手机格式错误")
        return jsonify(errno=RET.PARAMERR, errmsg="手机格式错误")
    # try:
    #     user = User.query.filter(User.mobile == mobile).first()
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg="查询错误")
    # if user:
    #     current_app.logger.error("用户已存在")
    #     return jsonify(errno=RET.PARAMERR, errmsg="用户已存在")
    # 3逻辑判断  redis数据库中real_image_code(是否过期)是否与image_code一致
    try:
        real_image_code = redis_store.get("Image_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="验证码过期")
    if real_image_code:
        try:
            redis_store.delete("Image_" + image_code_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.NODATA, errmsg="删除错误")
    else:
        current_app.logger.error("图片验证码过期")
        return jsonify(errno=RET.NODATA, errmsg="图片验证码过期")

    if image_code.lower() != real_image_code.lower():
        current_app.logger.error("参数错误")
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3.1发送短信验证码 先查询手机号是否被注册(之前写在前面)
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    if user:
        current_app.logger.error("用户已存在")
        return jsonify(errno=RET.DATAEXIST, errmsg="用户已存在")
    import random
    sms_code = random.randint(0, 999999)
    sms_code = "%06d" % sms_code
    # 调用ccp
    try:
        result = CCP().send_template_sms(mobile, {constants.SMS_CODE_REDIS_EXPIRES / 60, sms_code}, 1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    if result == -1:
        current_app.logger.error("发送失败")
        return jsonify(errno=RET.THIRDERR, errmsg="发送失败")
    print(sms_code)
    try:
        redis_store.setex("Sms_" + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存短信验证码异常")

    return jsonify(errno=RET.OK, errmsg="发送短信验证码成功")
